package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.user.pojos.ApChannel;
import com.heima.user.mapper.ApChannelMapper;
import com.heima.user.service.ApChannelService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;

@Service
@Slf4j
@Transactional
public class ApChannelServiceImpl extends ServiceImpl<ApChannelMapper, ApChannel> implements ApChannelService {
    
    @Resource
    private ApChannelMapper apChannelMapper;
    
    @Override
    public ApChannel getByWmChannelId(Integer wmChannelId) {
        // 由于目前没有直接关联字段，可以通过名称匹配等方式查找
        // 这里假设频道名称相同即为同一频道
        return null;
    }
    
    @Override
    public Integer syncWmChannel(Integer wmChannelId, String wmChannelName, Boolean isDefault, Boolean status) {
        // 查找是否已存在对应的用户端频道
        ApChannel apChannel = getOne(Wrappers.<ApChannel>lambdaQuery()
                .eq(ApChannel::getName, wmChannelName));
        
        if (apChannel == null) {
            // 如果不存在，则创建新的用户端频道
            apChannel = new ApChannel();
            apChannel.setName(wmChannelName);
            apChannel.setDescription("同步自自媒体频道");
            apChannel.setIsDefault(isDefault != null ? isDefault : false);
            apChannel.setStatus(status != null ? status : true);
            apChannel.setOrd(0); // 默认排序
            apChannel.setCreatedTime(new Date());
            apChannel.setUpdatedTime(new Date());
            save(apChannel);
        } else {
            // 如果存在，则更新频道信息
            apChannel.setIsDefault(isDefault != null ? isDefault : apChannel.getIsDefault());
            apChannel.setStatus(status != null ? status : apChannel.getStatus());
            apChannel.setUpdatedTime(new Date());
            updateById(apChannel);
        }
        
        return apChannel.getId();
    }
}
